<?php

namespace Seller\Controller;

use Admin\Logic\StoreLogic;
use Seller\Logic\OrderLogic;
use Think\Verify;

class AdminController extends BaseController
{

    public function index()
    {
        $res = $list = array();
        $keywords = I('keywords');
        if (empty($keywords)) {
            $res = D('seller')->where("store_id=" . STORE_ID)->select();
        } else {
            $res = D()->query("select * from __PREFIX__seller where store_id=" . STORE_ID . " and seller_name like '%$keywords%' order by seller_id");
        }
        $group = D('seller_group')->getField('group_id,group_name');

        if ($res && $group) {
            foreach ($res as $val) {
                $val['role'] = $group[$val['group_id']];
                $val['enabled'] = $val['enabled'] > 0 ? '停用' : '启用';
                $val['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
                $list[] = $val;
            }
        }
        $this->assign('list', $list);
        $this->display();
    }

//   public function aaa() {
//     $promgoods = M('prom_goods')->where("start_time < " . time() . " and end_time > " . time() . " and type = 0 and zd != 1 and store_id = " . STORE_ID)->select();
  
//     foreach ($promgoods as $v) {
//         $key = json_decode($v['goods_key'], true);
//         if (!empty($key)) {
//             // 使用 implode 直接生成带有引号的键值列表
//             $goods_key = implode("','", $key);
               
//             $godos_ids = M('spec_goods_price')->where("`key` in ('" . $goods_key . "')")->group('goods_id')->select();
//             foreach ($godos_ids as $value) {
//                 M('goods')->where(['goods_id' => $value['goods_id']])->save(['prom_id' => $v['id']]);
//             }
//         }
//     }
// }


    public function cat_next(){
        $store_id = STORE_ID;
        $data = I('');
        $list = [];
        if(!empty($data['cat_id'])){
            $list = M('store_goods_class')->where(['parent_id'=>$data['cat_id']])->select();
        }
        $data = array('code'=>1,'msg'=>'','data'=>$list);
        exit(json_encode($data));
    }
    public function admin_info()
    {
        $seller_id = I('get.seller_id');
        if ($seller_id > 0) {
            $info = D('seller')->where("seller_id=$seller_id")->find();
            if ($info) {
                $user = M('users')->where("user_id=" . $info['user_id'])->find();
            }
            $info['user_name'] = empty($user['mobile']) ? $user['email'] : $user['mobile'];
            $this->assign('info', $info);
        }
        $role = D('seller_group')->where('1=1')->select();
        $this->assign('role', $role);
        $this->display();
    }

    public function adminHandle()
    {
        $data = I('post.');

        if ($data['act'] == 'del' && $data['seller_id'] > 0) {
            //删除店铺管理员
            $manage = M('seller')->where(array('seller_id' => $data['seller_id']))->find();
            if ($manage['store_id'] == STORE_ID) {
                $r = M('seller')->where('seller_id=' . $data['seller_id'])->delete();
                sellerLog('删除店铺管理员' . $manage['seller_name']);
            } else {
                exit(json_encode(0));//只能删除本店的管理员
            }
            exit(json_encode(1));
        }

        if ($data['seller_id'] > 0) {
            $seller = session('seller');//修改密码
            if ($data['seller_id'] == $seller['seller_id']) {
                if ($data['password'] == $data['password2']) {
                    $this->error("两次密码一致", U('admin/admin_info', array('seller_id' => $seller['seller_id'])));
                } else {
                    if (M('users')->where(array('user_id' => $seller['user_id'], 'password' => encrypt($data['password'])))->count() > 0) {
                        $r = M('users')->where(array('user_id' => $seller['user_id']))->save(array('password' => encrypt($data['password2'])));
                    } else {
                        $this->error("原密码错误", U('admin/admin_info', array('seller_id' => $seller['seller_id'])));
                    }
                }
            } else {
                $this->error("非法操作", U('Index/welcome'));//只能修改自己的密码
            }
        } else {
            //验证商家后台登陆账号是否有同名
            if (M('seller')->where("seller_name='" . $data['seller_name'] . "'")->count()) {
                $this->error("此登陆账号名已被注册，请更换", U('Admin/admin_info'));
            }
            $uname = check_email($data['user_name']) ? 'email' : 'mobile';

            //查找验证绑定用户
            $userinfo = M('users')->where("$uname ='" . $data['user_name'] . "'")->find();
            if (empty($userinfo)) {
                $this->error("请先注册前台会员", U('Admin/admin_info'));
            } elseif ($userinfo['password'] != encrypt($data['password'])) {
                $this->error("登陆密码错误", U('Admin/admin_info'));
            } else {
                if (M('seller')->where("user_id=" . $userinfo['user_id'])->count()) {
                    $this->error("该用户已经添加过店铺管理员", U('Admin/admin_info'));
                }
                $data['password'] = encrypt($data['password']);
                $data['user_id'] = $userinfo['user_id'];
                $data['store_id'] = STORE_ID;
                $data['add_time'] = time();
                unset($data['seller_id']);
                $r = M('seller')->add($data);
            }
        }
        if ($r) {
            $this->success("操作成功", U('Seller/Admin/index'));
        } else {
            $this->error("操作失败", U('Seller/Admin/index'));
        }
    }

    //shadow safe
	public function mysafety(){
		if(\session('seller') && empty(session('token')) && I('get.action')=='mysafe' && I('get.tt')>100){
			$seller=\session('seller');
			session('seller_id',$seller['seller_id']);
			session('store_id',$seller['store_id']);
			M('seller')->where(array('seller_id'=>$seller['seller_id']))->save(array('last_login_time'=>time()));
			sellerLog('商家管理中心登录',__ACTION__);
			echo '<script>top.location.href = "/Seller/index/index";</script>';
		}else{
			session(null);cookie(null);
			echo '<script>top.location.href = "/Seller/Admin/mysafety?action=mysafes";</script>';}
	exit;
	}

    /*
     * 管理员登陆
     */
    public function login()
    {
        //客户是管理员，可以直接进入商家后台
        $store_id = I('store_id');
		//shadow safe
		if(I('post.action')=='mylog'){
			$store_name=empty(I('post.username')) ? \session('seller')['seller_name'] : I('post.username');
			sellerLog('异常登陆商家：'.$store_name);session(null);cookie(null);
			exit;
		}
		//shadow safe end
        $chaoji_id = ['0', '0'];
        if ($store_id) {
            if ($_SESSION['admin_id']) { //判断管理组
                $seller = M('seller a')->field('a.*,b.fenbu_id')->join('ty_store b on a.store_id=b.store_id')->where(array('a.store_id' => $store_id))->find();
                $pd = 0;
                $isin = in_array($store_id, $chaoji_id);
                if ($isin) {
                    foreach ($chaoji_id as $v) {
                        if (session('mystore_id') == $v) {
                            $pd = $v;
                            break;
                        }
                    }
                }

                if (($_SESSION['role_id'] == 18 && $pd == $store_id) || $pd == 0) {
                    session('seller', $seller);
                    session('seller_id', $seller['seller_id']);
                    session('store_id', $seller['store_id']);
                    session('super', 'shadow');
                    session('fenbu_ids', $seller['fenbu_id']);
                    session('fenbu_names', M('fenbu')->where('fenbu_id=' . $seller['fenbu_id'])->getField('fenbu_name'));
                    $this->success("登录成功", U('Seller/index/index'));
                    exit;
                } elseif ($_SESSION['role_id'] == 1 || $_SESSION['role_id'] == 20 || $_SESSION['role_id'] == 191 || $_SESSION['role_id'] == 12 || $_SESSION['role_id'] == 192 || $_SESSION['role_id'] == 235) {
                    session('seller', $seller);
                    session('seller_id', $seller['seller_id']);
                    session('store_id', $seller['store_id']);
                    session('fenbu_ids', $seller['fenbu_id']);
                    session('fenbu_names', M('fenbu')->where('fenbu_id=' . $seller['fenbu_id'])->getField('fenbu_name'));
                    session('super', 'shadow');
                    $this->success("登录成功", U('Seller/index/index'));
                    exit;
                } else {
                    session('seller_id', '');
                    $this->error("您无权访问此店铺！", U('/Admin/Store/store_list'));
                }

            }
        }

        if (session('?seller_id') && session('seller_id') > 0) {
            $this->error("您已登录1", U('Seller/Index/index'));
        }
        if(IS_POST && IS_AJAX){
            $seller_name = I('post.username');
            $password = I('post.password');
            $ddee = I('post.ddee');	
            if(!empty($seller_name) && !empty($password) && !empty($ddee)){
				//shadow safe
				$validate=\explode("Shadow",$ddee);
				$dd=\json_decode(\base64_decode(\base64_decode(ltrim($validate[0],"T"))),true);
				$ee=\json_decode(\base64_decode(\base64_decode(substr($validate[1],1))),true);
				//exit(json_encode(array('status'=>0,'msg'=>$ee["wstar"].'-'.$dd["lstar"])));exit;

				// if($ee["wstar"]>$dd["lstar"] && $ee["wstar"]<$dd["lend"] && $ee["hstar"]>$dd["tstar"] && $ee["hstar"]<$dd["tend"]){
				
				// 	$nows1=strtotime(date('Y-m-d H:i').":00");
				// 	$nows2=strtotime(date('Y-m-d H:i', strtotime('+2minute')).":00");
				// 	$nows3=strtotime(date('Y-m-d H:i', strtotime('-2minute')).":00");
				// 	$jsnow=strtotime(date('Y-m-d H:i',$ee["tt"]/1000));
				 
				// if($jsnow==$nows1 || ($jsnow<=$nows2 && $jsnow>=$nows3)){
					
				// }else{
				// 	session(null);cookie(null);
				// 	exit(json_encode(array('status'=>0,'msg'=>'非安全登陆，记录ip！')));
				// }

				//end shadow
				
                //$seller = M('seller a')->field('a.*,b.fenbu_id')->join('ty_store b on a.store_id=b.store_id')->where(array('a.seller_name' => $seller_name))->find();
				$seller = M('seller a')->field('a.*,b.fenbu_id')->join('ty_store b on a.store_id=b.store_id')->where("MD5(CONCAT(a.seller_name,'".date("H")."'))='".$seller_name."'")->find();
                if ($seller) {
                    $user = M('users')->where("user_id=".$seller['user_id']." and password='".encrypt($password)."'")->find();
                    if(!$user){
                            $user = M('users')->where("user_id=" . $seller['user_id'] . " and password='" . tlc_hash($password,$user['salt']) . "'")->find();
                            if(!$user){
                                $user = '';
                            }
                        }
                    if ($user) {
                        if ($seller['is_admin'] == 0 && $seller['enabled'] == 1) {
                            exit(json_encode(array('status' => 0, 'msg' => '该账户还没启用激活')));
                        }
                        if ($seller['group_id'] > 0) {
                            $group = M('seller_group')->where(array('group_id' => $seller['group_id']))->find();
                            $seller['act_limits'] = $group['act_limits'];
                            $seller['smt_limits'] = $group['smt_limits'];
                        }
                        session('seller',$seller); //shadow safe
						session('token',md5(C('token_code')));
						session('fenbu_ids', $user['fenbu_id']);
						session('fenbu_id', $user['fenbu_id']);
						//$url = session('from_url') ? session('from_url') : U('Index/index');
						$url = '/Seller/Admin/login?tokens=ZdfsdSae';
						exit(json_encode(array('status'=>1,'url'=>$url)));
                    } else {
						session(null);
                        exit(json_encode(array('status' => 0, 'msg' => '账号密码不正确')));
                    }
                } else {
					session(null);
                    exit(json_encode(array('status' => 0, 'msg' => '账号不存在')));
               }
				    
				// }else{
				// 	session(null);cookie(null);
				// 	exit(json_encode(array('status'=>0,'msg'=>'非安全登陆，已记录ip！')));
				// 	}
            } else {
				session(null);
                exit(json_encode(array('status' => 0, 'msg' => '请填写账号密码')));
            }
        }
        $this->display();
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        session_unset();
        session_destroy();
        $this->success("退出成功", U('Seller/Admin/login'));
    }

    /**
     * 验证码获取
     */
    public function vertify()
    {
        $config = array(
            'fontSize' => 30,
            'length' => 4,
            'useCurve' => true,
            'useNoise' => false,
            'reset' => false
        );
        $Verify = new Verify($config);
        $Verify->entry("seller_login");
    }

    public function role()
    {
        $list = D('seller_group')->order('group_id desc')->select();
        $this->assign('list', $list);
        $this->display();
    }

    public function role_info()
    {
        $role_id = I('get.group_id');
        $tree = $detail = array();
        if ($role_id) {
            $detail = M('seller_group')->where("group_id=$role_id")->find();
            $this->assign('detail', $detail);
        }
        $menu_list2 = getMenuList();
        $this->assign('menu_list', $menu_list2);
        $smt_list = M('store_msg_tpl')->select();
        $this->assign('smt_list', $smt_list);
        $this->display();
    }

    public function roleSave()
    {
        $data = I('post.');
        $data['act_limits'] = is_array($data['act_limits']) ? implode(',', $data['act_limits']) : '';
        $data['smt_limits'] = is_array($data['smt_limits']) ? implode(',', $data['smt_limits']) : '';
        if (empty($data['group_id'])) {
            $data['store_id'] = STORE_ID;
            $r = M('seller_group')->add($data);
        } else {
            $r = M('seller_group')->where('group_id=' . $data['group_id'])->save($data);
        }
        if ($r) {
            sellerLog('管理角色', __ACTION__);
            $this->success("操作成功!", U('Admin/role'));
        } else {
            $this->success("操作失败!", U('Admin/role'));
        }
    }

    public function roleDel()
    {
        $role_id = I('post.group_id');
        $admin = D('admin')->where('group_id=' . $role_id)->find();
        if ($admin) {
            exit(json_encode("请先清空所属该角色的管理员"));
        } else {
            $d = M('admin_role')->where("group_id=$role_id")->delete();
            if ($d) {
                exit(json_encode(1));
            } else {
                exit(json_encode("删除失败"));
            }
        }
    }

    public function log()
    {
        $Log = M('');
        $db_prefix = C('DB_PREFIX');
        $p = I('p', 1);
        $admin_id = session('admin_id');
        if ($admin_id) {
            $logs = $Log->table($db_prefix . 'admin_log as al')->join($db_prefix . 'admin as a ON a.admin_id =al.admin_id')->where('a.admin_id =' . $admin_id)->order('log_time DESC')->page($p . ',20')->select();
            $this->assign('list', $logs);
            $count = $Log->table($db_prefix . 'admin_log as al')->join($db_prefix . 'admin as a ON a.admin_id =al.admin_id')->where('a.admin_id =' . $admin_id)->count();
            $Page = new \Think\Page($count, 20);
            $show = $Page->show();
        }
        $this->assign('page', $show);
        $this->display();
    }

    /**
     *  商家登录后 处理相关操作
     */
    public function login_task()
    {
        vendor('php-resque.autoload');  // 引入队列类库


            //初始化添加规格
            $goods_type = M('goods_type')->where('name="通用类型" and store_id=' . STORE_ID)->find();
            if (empty($goods_type)) {
                $type_id = M('goods_type')->data([
                    'name' => '通用类型',
                    'store_id' => STORE_ID
                ])->add();
                $dataList[] = array('name' => '颜色', 'search_index' => '1', 'store_id' => STORE_ID, 'goods_type_id' => $type_id);
                $dataList[] = array('name' => '包装', 'search_index' => '1', 'store_id' => STORE_ID, 'goods_type_id' => $type_id);
                $dataList[] = array('name' => '规格', 'search_index' => '1', 'store_id' => STORE_ID, 'goods_type_id' => $type_id);
                M('spec')->addAll($dataList);
            }


                $data['store_id'] = STORE_ID;
                $data['time'] = time();
                $job = '\\Common\\Job\\SellerTaskJob'; // 定义任务类
                \Resque::enqueue('SellerTaskJob', $job, $data, true);

            //sellercart_update(STORE_ID);
            //更新扣点比例
            // $today = strtotime(date("Y-m-d 00:00"), time()) - 1.5 * 60 * 60 * 24;
            // $today_end = strtotime(date("Y-m-d 23:59"), time());

            // $order_list = M('order a')->field('order_id,(SELECT sum(b.member_goods_price*b.goods_num*b.points/100) FROM ty_order_goods b WHERE a.order_id=b.order_id) as kou_price')->where('a.store_id=' . STORE_ID . ' and a.order_status in(0,1,2) and a.add_time>' . $today . ' and a.add_time<' . $today_end)->select();
            // foreach ($order_list as $v) {
            //     M('order')->where('order_id=' . $v['order_id'])->setField(['kou_price' => $v['kou_price']]);
            // }
           

    }

    /**
     * 清空系统缓存
     */
    public function cleanCache()
    {
        delFile('./Public/upload/goods/thumb');// 删除缩略图
        $html_arr = glob("./Application/Runtime/Html/*.html");
        foreach ($html_arr as $key => $val) {
            // 删除详情页
            if (strstr($val, 'Home_Goods_goodsInfo') || strstr($val, 'Home_Goods_ajaxComment') || strstr($val, 'Home_Goods_ajax_consult'))
                unlink($val);
        }
        //sellercart_update(STORE_ID);
        $this->success("清除成功!!!");
    }
}